{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-08-28T04:12:07.230263Z",
     "start_time": "2018-08-28T04:12:07.224247Z"
    }
   },
   "outputs": [],
   "source": [
    "import random as rn\n",
    "import os\n",
    "os.environ['PYTHONHASHSEED'] = '0'\n",
    "np.random.seed(42)\n",
    "rn.seed(123)\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import seaborn as sns\n",
    "import pickle\n",
    "from sklearn.linear_model import SGDRegressor\n",
    "from sklearn.model_selection import PredefinedSplit\n",
    "from sklearn.metrics import r2_score\n",
    "from sklearn.model_selection import RandomizedSearchCV\n",
    "from scipy.stats import uniform\n",
    "from sklearn.cross_decomposition import PLSRegression\n",
    "pd.set_option('display.max_columns', 50)\n",
    "pd.set_option('display.max_rows', 100)\n",
    "pd.set_option('display.float_format', lambda x: '%.3f' % x)\n",
    "\n",
    "Path = 'D:\\\\APViaML'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-08-28T04:12:07.237281Z",
     "start_time": "2018-08-28T04:12:07.232268Z"
    }
   },
   "outputs": [],
   "source": [
    "def get_demo_dict_data():\n",
    "    file = open(Path + '\\\\data\\\\alldata_demo_top1000.pkl','rb')\n",
    "    raw_data = pickle.load(file)\n",
    "    file.close()\n",
    "    return raw_data\n",
    "def Evaluation_fun(predict_array,real_array):\n",
    "    List1 = []\n",
    "    List2 = []\n",
    "    if len(predict_array) != len(real_array):\n",
    "        print('Something is worng!')\n",
    "    else:\n",
    "        for i in range(len(predict_array)):\n",
    "            List1.append(np.square(predict_array[i]-real_array[i]))\n",
    "            List2.append(np.square(real_array[i]))\n",
    "        result = round(100*(1 - sum(List1)/sum(List2)),3)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-08-28T04:12:07.253324Z",
     "start_time": "2018-08-28T04:12:07.239287Z"
    },
    "code_folding": []
   },
   "outputs": [],
   "source": [
    "def rolling_pls_model_annual(\n",
    "    df_X ,\n",
    "    df_Y ,\n",
    "    tol_float = 1e-04 ,\n",
    "    max_iter_int= 1000):\n",
    "                                    \n",
    "    y_predict_list = []\n",
    "    num_comp_list = []\n",
    "    test_performance_score_list = []\n",
    "\n",
    "\n",
    "    for i in range(30):\n",
    "        print(i)\n",
    "        ## define data index\n",
    "        traindata_startyear_str = str(1958) \n",
    "        traindata_endyear_str = str(i + 1987) \n",
    "        vdata_startyear_str = str(i + 1976) \n",
    "        vdata_endyear_str = str(i + 1987) \n",
    "        testdata_startyear_str = str(i + 1988) \n",
    " \n",
    "        ## get data     \n",
    "        X_traindata =  np.array(df_X.loc[traindata_startyear_str:traindata_endyear_str])\n",
    "        Y_traindata = np.array(df_Y.loc[traindata_startyear_str:traindata_endyear_str])\n",
    "        X_vdata = np.array(df_X.loc[vdata_startyear_str:vdata_endyear_str])\n",
    "        Y_vdata = np.array(df_Y.loc[vdata_startyear_str:vdata_endyear_str])\n",
    "        X_testdata = np.array(df_X.loc[testdata_startyear_str])\n",
    "        Y_testdata = np.array(df_Y.loc[testdata_startyear_str])\n",
    "        \n",
    "        num_valid_size = len(X_traindata)-len(X_vdata)\n",
    "        ## model setting\n",
    "        v_score = pd.DataFrame(index=range(0,13,1),columns=['score'])\n",
    "        v_score['num'] = range(98,100,1)\n",
    "        v_temp_list =[]\n",
    "        for j in range(98,100,1):\n",
    "            v_predict_list=[]\n",
    "            k = j-1\n",
    "            PLS_model = PLSRegression( n_components = j ,\n",
    "                                      tol= tol_float ,\n",
    "                                      max_iter= max_iter_int )\n",
    "\n",
    "        ## model fitting\n",
    "            PLS_model.fit(X_traindata[num_valid_size:], Y_traindata[num_valid_size:])\n",
    "        ## model validation\n",
    "            v_pre_y_array = PLS_model.predict(X_vdata)\n",
    "            for x in v_pre_y_array[:,0]:\n",
    "                v_predict_list.append(x)\n",
    "            v_performance_score = Evaluation_fun(v_predict_list,Y_vdata)\n",
    "            v_temp_list.append(v_performance_score)\n",
    "        v_score['score'] = v_temp_list\n",
    "        v_score.sort_values(by='score',inplace=True,ascending=False)\n",
    "        best_num = v_score.iloc[0,1]\n",
    "        ##store the best num\n",
    "        num_comp_list.append(best_num)  \n",
    "        print(best_num)\n",
    "        ##refit the model\n",
    "        PLS_best_model = PLSRegression( n_components = best_num ,\n",
    "                                  tol= tol_float ,\n",
    "                                  max_iter= max_iter_int )\n",
    "        ##use the best pra to fit model\n",
    "        PLS_best_model.fit(X_traindata[:num_valid_size], Y_traindata[:num_valid_size])\n",
    "        \n",
    "        file = open(Path + '\\\\model\\\\pls\\\\' + testdata_startyear_str+ 'Model_OLS_Top1000_Prediction.pkl', 'wb')\n",
    "        pickle.dump(PLS_best_model, file)\n",
    "        file.close()\n",
    "        \n",
    "        ## model testing\n",
    "        test_pre_y_array = PLS_best_model.predict(X_testdata)\n",
    "        y_predict_list1=[]\n",
    "        ## get the predicion \n",
    "        for x in test_pre_y_array[:,0]:\n",
    "            y_predict_list.append(x)\n",
    "            y_predict_list1.append(x)\n",
    "        test_performance_score =  Evaluation_fun(y_predict_list1,Y_testdata )\n",
    "        test_performance_score_list.append(test_performance_score)    \n",
    "\n",
    "    return y_predict_list,num_comp_list,test_performance_score_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-08-28T04:12:07.732597Z",
     "start_time": "2018-08-28T04:12:07.255329Z"
    }
   },
   "outputs": [],
   "source": [
    "data = get_demo_dict_data()\n",
    "top_1000_data_X = data['X']\n",
    "top_1000_data_Y = data['Y']\n",
    "del data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-08-28T04:42:44.537228Z",
     "start_time": "2018-08-28T04:12:07.734603Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "99\n",
      "1\n",
      "99\n",
      "2\n",
      "99\n",
      "3\n",
      "99\n",
      "4\n",
      "99\n",
      "5\n",
      "99\n",
      "6\n",
      "99\n",
      "7\n",
      "99\n",
      "8\n",
      "99\n",
      "9\n",
      "99\n",
      "10\n",
      "99\n",
      "11\n",
      "99\n",
      "12\n",
      "99\n",
      "13\n",
      "99\n",
      "14\n",
      "99\n",
      "15\n",
      "99\n",
      "16\n",
      "99\n",
      "17\n",
      "99\n",
      "18\n",
      "99\n",
      "19\n",
      "99\n",
      "20\n",
      "99\n",
      "21\n",
      "99\n",
      "22\n",
      "99\n",
      "23\n",
      "99\n",
      "24\n",
      "99\n",
      "25\n",
      "99\n",
      "26\n",
      "99\n",
      "27\n",
      "99\n",
      "28\n",
      "99\n",
      "29\n",
      "99\n"
     ]
    }
   ],
   "source": [
    "y_predict_list,num_comp_list,test_performance_score_list = rolling_pls_model_annual(\n",
    "df_X = top_1000_data_X ,                                                                                \n",
    "df_Y = top_1000_data_Y )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-08-28T04:45:55.118128Z",
     "start_time": "2018-08-28T04:45:55.004819Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-16028.517"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_real = np.array(top_1000_data_Y.loc['1988':])\n",
    "Evaluation_fun(y_predict_list,y_real)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-08-28T04:42:44.716707Z",
     "start_time": "2018-08-28T04:42:44.709689Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[-268400.964,\n",
       " -36156.929,\n",
       " -11565.817,\n",
       " -17504.201,\n",
       " -102194.093,\n",
       " -2804.879,\n",
       " -108949.565,\n",
       " -71830.538,\n",
       " -1637.326,\n",
       " -3078.835,\n",
       " -808.24,\n",
       " -996.147,\n",
       " -1866.566,\n",
       " -4888.753,\n",
       " -3792.749,\n",
       " -2127.45,\n",
       " -2657.155,\n",
       " -1724.891,\n",
       " -2332.86,\n",
       " -1458.122,\n",
       " -1935.298,\n",
       " -33974.532,\n",
       " -9499.389,\n",
       " -12580.619,\n",
       " -9755.686,\n",
       " -778.594,\n",
       " -2297.879,\n",
       " -477.402,\n",
       " -7543.785,\n",
       " -9465.009]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test_performance_score_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-08-28T04:42:44.724728Z",
     "start_time": "2018-08-28T04:42:44.719715Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99,\n",
       " 99]"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "num_comp_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-08-28T04:42:44.855076Z",
     "start_time": "2018-08-28T04:42:44.727737Z"
    }
   },
   "outputs": [],
   "source": [
    "file = open(Path + '\\\\output\\\\data\\\\Model_PLS_Top1000_Prediction.pkl', 'wb')\n",
    "pickle.dump(y_predict_list, file)\n",
    "file.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "position": {
    "height": "460.8px",
    "left": "738px",
    "right": "20px",
    "top": "107px",
    "width": "591.8px"
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
